import React, { memo, useEffect, useState } from 'react';
import { Select } from 'antd';
import { querySalaryYearList } from '@/services/salaryManage/salaryCalculate';
import { getCurrentCompanyCode } from '@/pages/SalaryManage/utils'

const { Option } = Select;
const YearSelect = ({ value = '', onChange, organizationCode = getCurrentCompanyCode(), styles = {}, ...otherProps }) => {
    const [yearList, setYearList] = useState([]);
    const getYearList = async orgCode => {
        try {
            const { code, data = [] } = await querySalaryYearList(orgCode);
            if (code === 10000) {
                setYearList((data || []).map(y => ({
                    key: y,
                    label: `${y}年`
                })))
            }
        } catch (e) {
            console.log(e);
        }
    };
    useEffect(() => {
        if (organizationCode) {
            getYearList(organizationCode);
        }
    }, [organizationCode]);
    useEffect(() => {
        if (yearList.length) {
            const currentYear = value || new Date().getFullYear();
            const matchYear = yearList.find(item => item.key === currentYear);
            if (matchYear) {
                onChange(matchYear.key)
            } else {
                onChange(yearList[0].key)
            }
        }
    }, [yearList.length, value]);
    return <Select
        value={value}
        size="small"
        style={{ width: 90, marginRight: '8px', ...styles }}
        onSelect={key => {
            onChange(key);
        }}
        placeholder="请选择"
        {...otherProps}
    >
        {
            yearList.map(item =>
                <Option value={item.key} key={item.label}>{item.label}</Option>
            )
        }
    </Select>
};
export default memo(YearSelect)
